package org.rency.common.utils.validate;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.Assert;

public abstract class CommonValidator<T> {
	
	private ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	
	public void validator(T param){
		//注解校验
        validateBean(param);
        //内部校验
        innerValidator(param);
	}
	
	public void validateBean(T bean){
		List<String> errorList = new ArrayList<String>();
        Set<ConstraintViolation<T>> violations = factory.getValidator().validate(bean);
        if (!CollectionUtils.isEmpty(violations)) {
            for (ConstraintViolation<T> violation : violations) {
                errorList.add(violation.getMessage());
            }
        }
        Assert.isTrue(CollectionUtils.isEmpty(errorList), errorList.toString());
	}
	
	public abstract void innerValidator(T t);
	
}